import { useEffect, useState } from 'react';
import { TreeSelect } from 'antd';
import type { TreeSelectProps } from 'antd';
import { useBoolean } from 'ahooks';
import { debounce } from 'lodash-es';
import { getDeptTree } from 'src/api/modules/system';
import { IDeptRespData, OptionType } from 'src/interface';

export default function RoleSelect(props: TreeSelectProps) {
  const [loading, { setTrue, setFalse }] = useBoolean(false);
  const [treeData, setTreeData] = useState<OptionType[]>([]);

  const filterDataList = (data: IDeptRespData[]): OptionType[] => {
    return data.map((item) => {
      return {
        value: item.deptId,
        title: item.deptName,
        children: item.children ? filterDataList(item.children) : [],
      };
    });
  };

  const getRoleDataList = debounce(async (value?: string) => {
    setTrue();
    try {
      const deptTree = await getDeptTree({ deptName: value });
      const transformData = filterDataList(deptTree);
      setTreeData(transformData);
    } catch (err) {
      console.log(err);
    } finally {
      setFalse();
    }
  }, 300);

  useEffect(() => {
    getRoleDataList();
  }, []);

  return (
    <TreeSelect
      allowClear
      multiple
      {...props}
      onSearch={getRoleDataList}
      treeData={treeData}
      placeholder="请选择部门"
      loading={loading}></TreeSelect>
  );
}
